import { defineStore } from "pinia";

export interface TodoItem {
  id: number;
  name: string;
  isDone: boolean;
}

export type TodoList = TodoItem[];

interface TodoState {
  todoList: TodoList;
}

export default defineStore("todo", {
  state: (): TodoState => {
    return {
      // 如果数据中有引用数据类型就需要定义类型
      todoList: [
        { id: 1, name: "吃饭", isDone: false },
        { id: 2, name: "睡觉", isDone: true },
        { id: 3, name: "打王者", isDone: false },
      ],
    };
  },
  // state(): TodoState {
  //   return {
  //     todoList: [],
  //   };
  // },
  getters: {
    // 已完成数量
    isDoneNum(state) {
      return state.todoList.reduce((p, c) => {
        return p + (c.isDone ? 1 : 0);
      }, 0);
    },
    // 总数
    totalNum(state) {
      return state.todoList.length;
    },
  },
  actions: {
    // 添加todo
    addTodo(name: string) {
      this.todoList.push({
        id: Date.now(),
        name,
        isDone: false,
      });
    },
    // 删除todo
    removeTodo(id: number) {
      /*
        简单：push/unshift/splice..
        复杂：filter/map/reduce/some/every/find...
      */
      this.todoList = this.todoList.filter((todo) => todo.id !== id);
    },
    // 全选&全不选
    updateCheckAllTodo(checkAll: boolean) {
      this.todoList.forEach((todo) => (todo.isDone = checkAll));
    },
    // 单选
    updateTodo(id: number) {
      const todo = this.todoList.find((todo) => todo.id === id) as TodoItem;
      todo.isDone = !todo.isDone;
    },
    // 批量删除
    removeAllTodo() {
      this.todoList = this.todoList.filter((todo) => !todo.isDone);
    },
  },
});
